package cn.wolfcode.luowowo.website.interceptor;

import cn.wolfcode.luowowo.cache.service.IUserInfoRedisService;
import cn.wolfcode.luowowo.cache.util.RedisKeys;
import cn.wolfcode.luowowo.member.domain.UserInfo;
import cn.wolfcode.luowowo.website.annotation.LoginRequire;
import cn.wolfcode.luowowo.website.util.CookieUtil;
import com.alibaba.dubbo.config.annotation.Reference;
import org.springframework.web.method.HandlerMethod;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.handler.HandlerInterceptorAdapter;

import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 * 用户的登录检查
 * extends HandlerInterceptorAdapter  适配器模式
 * implements HandlerInterceptor
 */
public class CheckLoginInterceptor implements HandlerInterceptor {


    @Reference
    private IUserInfoRedisService userInfoRedisService;
    /**
     * 登录检查
     * @param request
     * @param response
     * @param handler
     * @return
     * @throws Exception
     */
    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {

        /*//1.获取token
        String token = CookieUtil.getToken(response, request);
        //2.通过token查询redis中是用户对象信息
        UserInfo userInfo = userInfoRedisService.getUserInfo(token);
        //3.判断用户对象信息是否存在，如果不存在直接到登录页面
        if(userInfo == null){
            response.sendRedirect("/login.html");
            return false;
        }
        //放行
        return true;*/

        //自定义注解方式拦截逻辑  @LoginRequire

        String token = CookieUtil.getToken(response, request);
        UserInfo userInfo = userInfoRedisService.getUserInfo(token);
        //1.获取当前请求方法对象
        //拦截器可以拦截所有请求，包括动态，静态，动态请求方法对象（HandlerMethod）
        if(handler instanceof HandlerMethod){
            HandlerMethod hm = (HandlerMethod) handler;
            //2.判断该请求方法是否贴有@LoginRequire
            if(hm.hasMethodAnnotation(LoginRequire.class)){
                //3.如果贴了，进行登陆检查
                if(userInfo == null){
                    response.sendRedirect("/login.html");
                    return false;
                }
            }
        }
        //4.没贴则放行
        //让所有请求都可以共享用户对象信息
        request.getSession().setAttribute("userInfo",userInfo);
        return true;
    }
}
